package com.jxq.ri.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @description: helloWord
 * @author: jxq
 * @date: 2021/7/31 10:19 上午
 * @version: 1.0
 **/
@RestController
public class ControllerRibbon {

    @Resource
    private LoadBalancerClient loadBalancerClient;

    private RestTemplate restTemplate1 = new RestTemplate();

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/ribbon/helloWord1")
    public Object helloWord(@RequestParam(value = "s") String s) {
        //第一种方式调用 直接调用
        String forObject = restTemplate1.getForObject("http://localhost:10830/client1/helloWord?s=" + s, String.class);
        return forObject;
    }

    @GetMapping("/ribbon/helloWord2")
    public Object helloWord2(@RequestParam(value = "s") String s) {
        //第二种调用方式 - 根据服务名 获取所有服务 根据算法选取某个服务 访问服务的网络位置
        ServiceInstance choose = loadBalancerClient.choose("EUREKA-CLIENT1");
        String forObject = restTemplate1.getForObject("http://" + choose.getHost() + ":" + choose.getPort() + "/client1/helloWord?s=" + s, String.class);
        return forObject;
    }

    @GetMapping("/ribbon/helloWord3")
    public Object helloWord3(@RequestParam(value = "s") String s) {
        //第三种方式  服务名注入
        String forObject = restTemplate.getForObject("http://EUREKA-CLIENT1/client1/helloWord?s=" + s, String.class);
        return forObject;
    }
}
